/* eslint-disable array-callback-return */
import React from 'react';
import { PlusOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Input, Table, Select, message, Modal, Row, Divider } from 'antd';
import { connect } from 'dva';
import { matchDict } from '@/utils/utils';
import HOCSelect from '@/components/AntDesign/Select';
import Area from '../../../components/Area';

const { Option } = Select;
const FormItem = Form.Item;
const { confirm } = Modal;

@connect(({ loading }) => ({
  loading: loading.models.custedit,
}))
class BasicList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dataSource: [],
      nowPage: 1,
      pageNum: 10,
      cmTotal: 10,
      custId: null,
      bankList: [],
      selectedRowKeys: [],
      isAdd: true,
      modalVisible: false,
    };

    this.columns = [
      {
        title: '城市',
        dataIndex: 'areaName',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '银行',
        dataIndex: 'bankId',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '开户行',
        dataIndex: 'bankOfDepoName',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '银行账号',
        dataIndex: 'bankAcco',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '开户单位名称',
        dataIndex: 'accoHolderName',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '备注',
        dataIndex: 'remark',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record) => (
          <span className="editable-row-operations">
            <a
              onClick={e => this.update(e, record.bankAccoId, record.mailProvince, record.mailCity)}
            >
              修改
            </a>
            <Divider type="vertical" />
            <a onClick={e => this.delList(e, record)}>删除</a>
          </span>
        ),
      },
    ];
  }

  componentDidMount = () => {
    const { custId, bankList } = this.props;
    const { nowPage, pageNum } = this.state;
    this.setState({ custId, bankList }, () => {
      this.getList(nowPage, pageNum);
    });
    this.getAreaList('', data => {
      data.map(item => {
        const temp = item;
        temp.label = item.areaName;
        temp.value = item.areaId;
        temp.isLeaf = false;
      });
    });
  };

  // 获取列表数据
  getList = (nowPage, pageNum) => {
    const { custId, dispatch } = this.props;
    const { bankList } = this.state;
    const pageArg = {
      currentPage: nowPage,
      pageSize: pageNum,
      orderBy: ' BANK_ACCO_ID DESC',
    };
    const params = { custId, pageArg };
    dispatch({
      type: 'custedit/getBankList',
      payload: params,
    }).then(res => {
      if (res.success) {
        const data = res.data.pageRecords;
        data.map(item => {
          const temp = item;
          if (item.areaName === '市辖区' || item.areaName === '市辖县' || item.areaName === '县') {
            temp.areaName = item.areaParentName;
          }
          temp.bankId = matchDict(bankList, item.bankId);
          Object.keys(item).forEach(key => {
            const obj = item;
            if (item[key] == null) {
              obj[key] = '暂无';
            }
          });
        });
        this.setState({ dataSource: data, cmTotal: res.data.totalCount });
      } else {
        this.setState({ cmTotal: 0, dataSource: [] });
        message.warning(`${res.message || '暂无数据！'}`);
      }
    });
  };

  // 查询省市区
  getAreaList = (areaId, callback) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'custedit/getAreaList',
      payload: {
        parentId: areaId,
      },
    }).then(res => {
      callback(res.data);
    });
  };

  // 删除数据
  delList = (e, record) => {
    e.preventDefault();
    const { selectedRowKeys } = this.state;
    const { dispatch } = this.props;
    const rowKeys = [];
    const rows = [];
    rowKeys.push(record.bankAccoId);
    rows.push(record);
    this.setState({ selectedRowKeys: rowKeys });
    confirm({
      icon: <QuestionCircleOutlined />,
      title: '你确定要刪除此条银行账户信息吗？',
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      style: { top: 200 },
      onOk: () => {
        dispatch({
          type: 'custedit/deleteBankAccount',
          payload: {
            generalIds: rowKeys,
          },
        }).then(res => {
          if (res.success) {
            const { cmTotal, nowPage, pageNum } = this.state;
            const selectedLen = selectedRowKeys.length;
            if (nowPage > 1 && (cmTotal % pageNum === selectedLen || pageNum === selectedLen)) {
              this.getList(nowPage - 1, pageNum);
              this.setState({ nowPage: nowPage - 1 });
            } else {
              this.getList(nowPage, pageNum);
            }
            this.setState({ selectedRowKeys: [] });
            message.success('删除成功！');
          } else {
            message.warning(`${res.message || '删除失败！'}`);
          }
        });
      },
    });
  };

  // 新增数据
  add = () => {
    const { form } = this.props;
    this.handleModalVisible(true, true);
    form.resetFields();
  };

  // 修改数据
  update = (e, bankAccoId) => {
    e.preventDefault();
    const { custId, dispatch, form } = this.props;
    const rowKeys = [];
    rowKeys.push(bankAccoId);
    this.setState({ selectedRowKeys: rowKeys });
    if (custId) {
      dispatch({
        type: 'custedit/getBankAccount',
        payload: {
          bankAccoId,
        },
      }).then(res => {
        this.setState({ custId });
        if (res.success && res.data) {
          this.handleModalVisible(true, false);
          const getFieldsList = form.getFieldsValue();
          Object.keys(getFieldsList).forEach(key => {
            if (res.data[key]) {
              if (key === 'bankId') {
                form.setFieldsValue({ [key]: { key: `${res.data[key]}` } });
              } else if (key === 'areaId') {
                form.setFieldsValue({
                  [key]: { key: res.data.areaId, label: res.data.areaName },
                });
              } else {
                form.setFieldsValue({ [key]: res.data[key] });
              }
            }
          });
        } else {
          message.warning(`${res.message || '暂无数据！'}`);
        }
      });
    }
  };

  // 切换模态框：新增、修改
  handleModalVisible = (flag, isAdd) => {
    this.setState({
      modalVisible: !!flag,
      isAdd,
    });
  };

  // 取消关闭模态框
  cancelModal = () => {
    this.handleModalVisible(false, true);
    this.setState({ selectedRowKeys: [] });
  };

  getData = (value, id) => {
    const { form } = this.props;
    if (id) {
      form.setFieldsValue({ [id]: value });
      this.setState({ [id]: value });
    }
  };

  // 新增修改提交数据
  submitData = () => {
    const { isAdd, custId, selectedRowKeys, nowPage, pageNum } = this.state;
    const { form, dispatch } = this.props;
    let submitData = {};
    const submitUrl = isAdd ? 'custedit/bankInsert' : 'custedit/bankUpdate';
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const temp = values;
        const areaArrayOne = values.areaId[0];
        const areaArrayTwo = values.areaId[1];
        temp.mailProvince = areaArrayOne;
        temp.mailCity = areaArrayTwo;
        temp.areaId = values.areaId;
        Object.keys(values).forEach(key => {
          const obj = values;
          if (values[key] && values[key].key) {
            obj[key] = values[key].key;
          } else {
            obj[key] = values[key] ? values[key] : '';
          }
        });
        submitData = isAdd
          ? { custId, ...values }
          : { custId, ...values, bankAccoId: selectedRowKeys[0] };
        dispatch({
          type: submitUrl,
          payload: submitData,
        }).then(res => {
          this.setState({ modalVisible: false });
          if (res.success) {
            message.success(`${res.message || (isAdd ? '新增成功！' : '修改成功！')}`);
            this.getList(nowPage, pageNum);
            this.setState({ selectedRowKeys: [] });
          } else {
            message.warning(`${res.message || (isAdd ? '新增失败！' : '修改失败！')}`);
          }
        });
      }
    });
  };

  render() {
    const {
      dataSource,
      selectedRowKeys,
      modalVisible,
      isAdd,
      nowPage,
      pageNum,
      cmTotal,
      bankList,
    } = this.state;
    const {
      loading,
      form: { getFieldDecorator },
    } = this.props;
    // 表格配置：行选择
    const rowSelection = {
      selectedRowKeys,
      onChange: rows => {
        this.setState({ selectedRowKeys: rows });
      },
    };
    // 表格配置：分页器
    const pagination = {
      defaultCurrent: nowPage, // 默认当前页
      defaultPageSize: pageNum, // 默认单页条数
      current: nowPage, // 当前页
      pageSize: pageNum, // 单页条数
      total: cmTotal, // 数据总数
      showQuickJumper: true, // 跳转至某页
      showSizeChanger: true, // 是否可以改变 pageSize
      onChange: (page, pageSize) => {
        // 页码改变的回调
        this.setState({ nowPage: page, pageNum: pageSize });
        this.getList(page, pageSize);
      },
      onShowSizeChange: (current, size) => {
        // 单页条数变化的回调
        this.setState({ nowPage: current, pageNum: size });
        this.getList(current, size);
      },
      showTotal: total => {
        const totalPage = total < pagination.pageSize ? 1 : Math.ceil(total / pagination.pageSize);
        return `共 ${total} 条记录 第 ${nowPage} / ${totalPage}页`;
      },
    };
    // 模态框布局
    const formItemLayoutModal = {
      labelCol: { md: { span: 6 } },
      wrapperCol: { md: { span: 16, offset: 1 } },
    };
    // 模态框配置
    const modalConfig = {
      title: isAdd ? '新增银行账户信息' : '修改银行账户信息',
      visible: modalVisible,
      confirmLoading: loading,
      onOk: this.submitData,
      okText: '提交',
      onCancel: this.cancelModal,
      destroyOnClose: true,
    };
    return (
      <div>
        <Row style={{ marginBottom: '20px' }}>
          <Button type="primary" onClick={this.add}>
            <PlusOutlined />
            新增
          </Button>
        </Row>
        <Table
          rowSelection={rowSelection}
          dataSource={dataSource}
          columns={this.columns}
          rowKey={record => record.bankAccoId}
          loading={loading}
          pagination={pagination}
        />
        <Modal {...modalConfig}>
          <Form layout="horizontal">
            <FormItem {...formItemLayoutModal} label="城市">
              {getFieldDecorator('areaId', {
                rules: [{ required: true, message: '请选择' }],
              })(<Area getData={this.getData} labelInValue />)}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="银行">
              {getFieldDecorator('bankId', {
                rules: [{ required: true, message: '请选择' }],
              })(
                <HOCSelect
                  placeholder="请输入关键字检索"
                  style={{ width: '100%' }}
                  labelInValue
                  showSearch
                  optionFilterProp="children"
                >
                  {bankList.length
                    ? bankList.map(options => (
                      <Option key={options.itemCode}>{options.itemName}</Option>
                    ))
                    : null}
                </HOCSelect>
              )}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="开户行">
              {getFieldDecorator('bankOfDepoName', {
                rules: [{ required: true, message: '请输入' }],
              })(<Input placeholder="请输入" maxLength={100} />)}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="银行账号">
              {getFieldDecorator('bankAcco', {
                rules: [
                  { required: true, message: '最大长度不超过25的数字', pattern: /^\d{1,25}$/ },
                ],
              })(<Input placeholder="请输入" maxLength={25} />)}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="开户单位名称">
              {getFieldDecorator('accoHolderName', {
                rules: [{ required: true, message: '请输入' }],
              })(<Input placeholder="请输入" maxLength={100} />)}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="备注">
              {getFieldDecorator('remark', {
                rules: [{ required: false, message: '请选择' }],
              })(<Input placeholder="请输入" maxLength={200} />)}
            </FormItem>
          </Form>
        </Modal>
      </div>
    );
  }
}
const ListSearchForm = Form.create()(BasicList);
export default ListSearchForm;
